package guo.myapp.spitter.controller;

import guo.myapp.spitter.Spitter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/spitter")
public class SpitterController {

    Map<String,Object> map = new HashMap<>();

//    @RequestMapping(value = "/", method = RequestMethod.GET)
//    public ModelAndView test() {
//        return new ModelAndView("home");
//    }

//    @RequestMapping(value = "/spitter", method = RequestMethod.POST)
//    public void spitter(Spitter spitter) {
//        System.out.println(spitter);
//    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegisterForm(Model model) {
        model.addAttribute(new Spitter());

        return "registerForm";
    }

    @RequestMapping("/{spitterId}")
    public String spitter(Model model, @PathVariable String spitterId){
        if(map.containsKey(spitterId)){
            model.addAttribute("spitter",map.get(spitterId));
            return "spitterInfo";
        }
        return "redirect:/spitter/register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String processRegistration(@Valid Spitter spitter, Errors errors){
//        System.out.println(errors.hasErrors());
            if(errors.hasErrors()) {
            return "registerForm";
        }
        map.put(spitter.getId()+"",spitter);
        return "redirect:/spitter/"+spitter.getId();
    }
}
